import { FC, ReactNode } from 'react';
import { Drawer } from 'antd';
import type { FormInstance, FormItemProps } from 'antd/lib/form';
import { observer } from 'mobx-react';
import _ from 'lodash';

import Button from '@components/Button';
import Form, { Item as FormItem } from '@components/Form';

export type EditDrawerFormProps = {
  /** 抽屉标题 */
  title?: ReactNode;

  /** 表单初始化值 */
  initialValues?: { [key: string]: any };

  /** 表单实例 */
  form: FormInstance<any>;

  /** 表单配置 */
  formItems: FormItemProps[];

  /**
   * 抽屉打开状态
   * @default false
   */
  openFlag: boolean;

  /** 设置 抽屉打开状态 */
  setOpenFlag?: (openFlag: boolean) => void;

  /** 保存 */
  handleSave?: () => void;

  /**
   * 加载状态
   * @default false
   */
  loading?: boolean;
};

const EditDrawerForm: FC<EditDrawerFormProps> = ({
  title = '详情',
  initialValues = {},
  form,
  formItems = [],
  openFlag = false,
  setOpenFlag,
  handleSave,
  loading = false
}) => {
  return (
    <Drawer
      title={title}
      placement="right"
      maskClosable={false}
      destroyOnClose
      onClose={() => {
        if (_.isFunction(setOpenFlag)) setOpenFlag(false);
      }}
      open={openFlag}
      width={500}
      extra={
        _.isFunction(handleSave) && (
          <Button type="primary" onClick={() => handleSave()} loading={loading}>
            保存
          </Button>
        )
      }
    >
      <Form loading={loading} form={form} initialValues={initialValues}>
        {formItems.map((item: any) => (
          <FormItem key={item.name} {...item} />
        ))}
      </Form>
    </Drawer>
  );
};

export default observer(EditDrawerForm);
